package cubelabs.nexus.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cubelabs.nexus.domain.MessageDTO;
import cubelabs.nexus.entity.User;
import cubelabs.nexus.enums.MessageStatus;
import cubelabs.nexus.enums.MessageType;
import cubelabs.nexus.service.NexusService;
import cubelabs.nexus.utils.GenericUtils;

@Controller
public class MessageController {

	@Autowired
	private NexusService nexusService;
	
	@RequestMapping(value = "/message", method=RequestMethod.POST)
	public @ResponseBody
	String sendChatMessage(@RequestBody MessageDTO messageDTO, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			User frmUser = (User) request.getSession().getAttribute("user");
			//if(frmUser.getId() != messageDTO.fromUser.getId()) return "UNAUTHORIZED";
			messageDTO.setMessageStatus(MessageStatus.CREATED);
			messageDTO.setMessageType(MessageType.CHAT);
			messageDTO.setFromUser(GenericUtils.getUserDTO(frmUser));
			nexusService.createOrUpdateMessage(messageDTO);
			return "SUCCESS";
		} catch (Exception e) {
			e.printStackTrace();
			return "FAIL";
		}
	}
	
	@RequestMapping(value = "/message", method=RequestMethod.GET)
	public @ResponseBody
	List<MessageDTO> listMessages(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			User user = (User) request.getSession().getAttribute("user");
			return nexusService.getUserMessages(user, new Date());
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
}
